package com.questetra.bpms.android;

import java.io.IOException;
import java.net.URLEncoder;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import com.google.api.client.http.HttpResponseException;

public class ConnectionService extends Service {
    @Override
    public void onCreate() {
        super.onCreate();
		// Toast toast = Toast.makeText(getApplicationContext(),
		// "onCreate()",
		// Toast.LENGTH_SHORT);
		// toast.show();
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
		// Toast toast = Toast.makeText(getApplicationContext(),
		// "onStart()",
		// Toast.LENGTH_SHORT);
		// toast.show();

        String url = "/API/OR/Workitem/list?option=OPERATING&offerDatetime=+"
                + URLEncoder.encode("#{#now.addHours(-1)}");

        try {
            final String json = OAuthService.getInstance().getResponse(url);

            String ns = Context.NOTIFICATION_SERVICE;
            NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);

            int icon = R.drawable.icon48;
            CharSequence tickerText = "Hello";
            long when = System.currentTimeMillis();
            Notification notification = new Notification(icon, tickerText, when);

            Context context = getApplicationContext();
            CharSequence contentTitle = "My notification";
            CharSequence contentText = json;
            Intent notificationIntent = new Intent(this,
                                                   WorkitemListActivity.class);
            PendingIntent contentIntent = PendingIntent.getActivity(this,
                                                                    0,
                                                                    notificationIntent,
                                                                    0);
            notification.setLatestEventInfo(context,
                                            contentTitle,
                                            contentText,
                                            contentIntent);

            mNotificationManager.notify(1, notification);
        } catch (HttpResponseException e) {
            Log.w("JSON", e);
            if (e.response.statusCode == 401) {
                Preferences.removeToken(getApplicationContext());
            }
        } catch (IOException e) {
            Log.w("JSON", e);
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
		// Toast toast = Toast.makeText(getApplicationContext(),
		// "onDestroy()",
		// Toast.LENGTH_SHORT);
		// toast.show();
        super.onDestroy();
    }
}
